package br.com.amadeus.android.dao;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import br.com.amadeus.android.entities.Action;
import br.com.amadeus.android.entities.Goal;
import br.com.amadeus.android.entities.Resource;
import br.com.amadeus.android.entities.Task;
import br.com.amadeus.android.util.Util;

public class TaskDAO {
	public static String[] columns = new String[] { TaskDAO.ID,
			TaskDAO.BEGINDATE, TaskDAO.ENDDATE, TaskDAO.RESOLVED,
			TaskDAO.ACTION_ID, TaskDAO.RESOURCE_ID, TaskDAO.GOAL_ID };

	public static final String ID = "_id";
	public static final String BEGINDATE = "begin_date";
	public static final String ENDDATE = "end_date";
	public static final String RESOLVED = "resolved";
	public static final String ACTION_ID = "action_id";
	public static final String RESOURCE_ID = "resource_id";
	public static final String GOAL_ID = "goal_id";

	private SQLiteDatabase db;

	private static TaskDAO instance = new TaskDAO();

	public static TaskDAO getInstance(Context context) {

		if (instance.db == null || !instance.db.isOpen()) {
			DBHelper helper = new DBHelper(context);
			instance.db = helper.getWritableDatabase();
		}
		return instance;
	}

	public TaskDAO() {
	}

	public long save(Task task) {
		long id = task.getId();
		if (id == 0) {
			return insert(task);
		} else {
			return update(task);
		}
	}

	private long insert(Task task) {
		long id_task = -1;

		db.beginTransaction();
		try {

			ContentValues values = new ContentValues();
			values.put(TaskDAO.BEGINDATE, task.getBeginDate());
			values.put(TaskDAO.ENDDATE, task.getEndDate());
			values.put(TaskDAO.RESOLVED, task.isResolved());
			values.put(TaskDAO.ACTION_ID, task.getAction().getId());
			values.put(TaskDAO.RESOURCE_ID, task.getResource().getId());
			values.put(TaskDAO.GOAL_ID, task.getGoal().getId());

			id_task = db.insert(DBHelper.TABLE_TASK, null, values);
			if (id_task != -1)
				db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}

		return id_task;
	}

	private long update(Task task) {
		boolean deuErro = false;

		db.beginTransaction();
		try {
			ContentValues values = new ContentValues();
			values.put(TaskDAO.BEGINDATE, task.getBeginDate());
			values.put(TaskDAO.ENDDATE, task.getEndDate());
			values.put(TaskDAO.RESOLVED, task.isResolved());
			values.put(TaskDAO.ACTION_ID, task.getAction().getId());
			values.put(TaskDAO.RESOURCE_ID, task.getResource().getId());
			values.put(TaskDAO.GOAL_ID, task.getGoal().getId());

			deuErro = db.update(DBHelper.TABLE_TASK, values, TaskDAO.ID
					+ " = ?", new String[] { String.valueOf(task.getId()) }) == 0;

			if (!deuErro)
				db.setTransactionSuccessful();

		} finally {
			db.endTransaction();
		}
		return task.getId();
	}

	public void delete(int id) {
		db.beginTransaction();
		try {
			db.delete(DBHelper.TABLE_TASK, TaskDAO.ID + "=?",
					new String[] { String.valueOf(id) });
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
	}
	
	public Task getTask(int id) {
		Task task = null;
		Cursor c = db.query(DBHelper.TABLE_TASK, null, TaskDAO.ID + "=" + id,
				null, null, null, null);
		if (c.getCount() > 0) {
			c.moveToFirst();
			task = fillTask(c);
		}
		c.close();
		return task;
	}

	protected static Task fillTask(Cursor c) {
		int id = c.getInt(c.getColumnIndex(TaskDAO.ID));
		/*Date beginDate = Util.getDate(
				c.getString(c.getColumnIndex(TaskDAO.BEGINDATE)),
				Util.FORMATO_DATA_BD);
		Date endDate = Util.getDate(
				c.getString(c.getColumnIndex(TaskDAO.ENDDATE)),
				Util.FORMATO_DATA_BD);*/
		String beginDate = c.getString(c.getColumnIndex(GoalDAO.BEGINDATE));
		String endDate = c.getString(c.getColumnIndex(GoalDAO.ENDDATE));
		boolean resolved;
		if (c.getString(c.getColumnIndex(TaskDAO.RESOLVED)).equals("TRUE")
				|| c.getString(c.getColumnIndex(TaskDAO.RESOLVED)) != "TRUE")
			resolved = true;
		else
			resolved = false;
		
		Action action = new Action(c.getInt(c
				.getColumnIndex(TaskDAO.ACTION_ID)));
		Resource resource = new Resource(c.getInt(c
				.getColumnIndex(TaskDAO.RESOURCE_ID)));
		Goal goal = new Goal(c.getInt(c
				.getColumnIndex(TaskDAO.GOAL_ID)));

		return new Task(id, beginDate, endDate, resolved, action, resource, goal);
	}
	
	protected Task getTaskFull(int id){
		Cursor c = db.query(DBHelper.TABLE_TASK, null, TaskDAO.ID + "=" + id,
				null, null, null, null);
		if (c.getCount() > 0) {
			c.moveToFirst();
			return fillTaskFull(c);
		}
		return null;
	}

	private Task fillTaskFull(Cursor c) {
		int id = c.getInt(c.getColumnIndex(TaskDAO.ID));
		/*Date beginDate = Util.getDate(
				c.getString(c.getColumnIndex(TaskDAO.BEGINDATE)),
				Util.FORMATO_DATA_BD);
		Date endDate = Util.getDate(
				c.getString(c.getColumnIndex(TaskDAO.ENDDATE)),
				Util.FORMATO_DATA_BD);*/
		String beginDate = c.getString(c.getColumnIndex(GoalDAO.BEGINDATE));
		String endDate = c.getString(c.getColumnIndex(GoalDAO.ENDDATE));
		boolean resolved;
		if (c.getString(c.getColumnIndex(TaskDAO.RESOLVED)).equals("TRUE")
				|| c.getString(c.getColumnIndex(TaskDAO.RESOLVED)) != "TRUE")
			resolved = true;
		else
			resolved = false;
		Action action = new Action(c.getInt(c
				.getColumnIndex(TaskDAO.ACTION_ID)));
		Resource resource = new Resource(c.getInt(c
				.getColumnIndex(TaskDAO.RESOURCE_ID)));
		Goal goal = new Goal(c.getInt(c
				.getColumnIndex(TaskDAO.GOAL_ID)));
	
		Cursor ac = db.query(DBHelper.TABLE_ACTION, null, ActionDAO.ID + "=" + action.getId(),
				null, null, null, null);
		if (ac.getCount() > 0) {
			ac.moveToFirst();
			action = ActionDAO.fillAction(ac);
		}
		
		Cursor rc = db.query(DBHelper.TABLE_RESOURCE, null, ResourceDAO.ID + "=" + resource.getId(),
				null, null, null, null);
		if (ac.getCount() > 0) {
			ac.moveToFirst();
			resource = ResourceDAO.fillResource(rc);
		}
		
		Cursor gc = db.query(DBHelper.TABLE_GOAL, null, GoalDAO.ID + "=" + goal.getId(),
				null, null, null, null);
		if (ac.getCount() > 0) {
			ac.moveToFirst();
			goal = GoalDAO.fillGoal(gc);
		}
		
		return new Task(id, beginDate, endDate, resolved, action, resource, goal);
	}
	
	public ArrayList<Task> getAllTasksByGoal(int goal_id){
		ArrayList<Task> taskList = new ArrayList<Task>();
		
		Cursor c = db.query(DBHelper.TABLE_TASK, null, TaskDAO.GOAL_ID+"="+ goal_id,
				null, null, null, null);
		if (c.getCount() > 0) {
			c.moveToFirst();
			do {
				
				taskList.add(fillTask(c));
				
			} while (c.moveToNext());
				
		}
		c.close();
		return taskList;
		
	}
	
	public ArrayList<Task> getTaskList(){
		ArrayList<Task> taskList = new ArrayList<Task>();
		
		Cursor c = db.query(DBHelper.TABLE_TASK, null, null,
				null, null, null, null);
		if (c.getCount() > 0) {
			c.moveToFirst();
			do {
				taskList.add(fillTask(c));
			} while (c.moveToNext());
		}
		c.close();
		return taskList;
	}

}
